<template>
  <div class="trend-chart">
    <div class="chart-controls">
      <div class="time-range-selector">
        <button 
          v-for="range in timeRanges" 
          :key="range.value"
          :class="{ active: selectedRange === range.value }"
          @click="selectRange(range.value)"
        >
          {{ range.label }}
        </button>
      </div>
    </div>
    <ChartWrapper :options="chartOptions" :loading="loading" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { EChartsOption } from 'echarts'
import type { TrendChartProps, TimeSeriesData } from '@/types'
import ChartWrapper from './ChartWrapper.vue'

const props = withDefaults(defineProps<TrendChartProps>(), {
  showGradient: true,
  showGlow: true,
  interactive: true
})

const emit = defineEmits<{
  rangeChange: [start: Date, end: Date]
}>()

const loading = ref(false)
const selectedRange = ref(30)

const timeRanges = [
  { label: '7天', value: 7 },
  { label: '30天', value: 30 },
  { label: '90天', value: 90 },
  { label: '全部', value: 365 }
]

// 过滤数据
const filteredData = computed(() => {
  const [start, end] = props.timeRange
  return props.data.filter(d => d.timestamp >= start && d.timestamp <= end)
})

// 按指标分组数据
const groupedData = computed(() => {
  const groups: Record<string, TimeSeriesData[]> = {}
  
  filteredData.value.forEach(item => {
    if (!groups[item.metric]) {
      groups[item.metric] = []
    }
    groups[item.metric].push(item)
  })
  
  return groups
})

// 数据抽样（超过 1000 个点时）
function sampleData(data: TimeSeriesData[], maxPoints: number = 1000): TimeSeriesData[] {
  if (data.length <= maxPoints) return data
  
  const step = Math.ceil(data.length / maxPoints)
  return data.filter((_, index) => index % step === 0)
}

// 生成图表配置
const chartOptions = computed<EChartsOption>(() => {
  const series = props.metrics.map((metric, index) => {
    const data = groupedData.value[metric] || []
    const sampledData = sampleData(data)
    
    const colors = ['#00f3ff', '#ff00ff', '#00ff88', '#ffaa00', '#ff3366']
    const color = colors[index % colors.length]
    
    return {
      name: metric,
      type: 'line',
      smooth: true,
      data: sampledData.map(d => [d.timestamp, d.value]),
      lineStyle: {
        width: 2,
        shadowColor: props.showGlow ? `${color}80` : 'transparent',
        shadowBlur: props.showGlow ? 10 : 0
      },
      areaStyle: props.showGradient ? {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: `${color}60` },
            { offset: 1, color: `${color}10` }
          ]
        }
      } : undefined,
      emphasis: {
        focus: 'series',
        lineStyle: {
          width: 3
        }
      }
    }
  })

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#1a1f3a'
        }
      }
    },
    legend: {
      data: props.metrics,
      top: 10,
      textStyle: {
        color: '#ffffff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#495670'
        }
      },
      axisLabel: {
        color: '#8892b0'
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.05)'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#495670'
        }
      },
      axisLabel: {
        color: '#8892b0'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
          type: 'dashed'
        }
      }
    },
    series,
    dataZoom: props.interactive ? [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        backgroundColor: 'rgba(26, 31, 58, 0.5)',
        dataBackgroundColor: 'rgba(0, 243, 255, 0.2)',
        fillerColor: 'rgba(0, 243, 255, 0.3)',
        handleStyle: {
          color: '#00f3ff'
        },
        textStyle: {
          color: '#8892b0'
        }
      }
    ] : undefined
  }
})

function selectRange(days: number) {
  selectedRange.value = days
  const end = new Date()
  const start = new Date(end.getTime() - days * 24 * 60 * 60 * 1000)
  emit('rangeChange', start, end)
}

// 监听数据变化
watch(() => props.data, () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 300)
}, { deep: true })
</script>

<style lang="scss" scoped>
.trend-chart {
  width: 100%;
  height: 100%;
}

.chart-controls {
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-range-selector {
  display: flex;
  gap: 0.5rem;
  
  button {
    padding: 0.5rem 1rem;
    background: transparent;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 6px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.875rem;
    
    &:hover {
      border-color: var(--color-primary);
      color: var(--text-primary);
    }
    
    &.active {
      background: var(--color-primary);
      border-color: var(--color-primary);
      color: var(--bg-primary);
      box-shadow: 0 0 10px var(--color-primary);
    }
  }
}
</style>
